/*
 * Copyright 2011 Romain Gilles
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jvdb;


import org.slf4j.Logger;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by IntelliJ IDEA.
 * User: romain.gilles
 * Date: 1/14/11
 * Time: 2:47 PM
 * To change this template use File | Settings | File Templates.
 */
class StatementHandler implements InvocationHandler {
    private final Logger logger;

    final Object jdbcObj;

    StatementHandler(Logger logger, Object jdbcObj) {
        this.logger = logger;
        this.jdbcObj = jdbcObj;
    }


    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (isExecMethod(method)) {
            long start = System.nanoTime();
            Object result = doInvoke(method, args);
            long end = System.nanoTime();
            logExec(start, end);
            return result;
        }
        return doInvoke(method, args);
    }

    private void logExec(long start, long end) {
        logger.info("%s {executed (start:%d, end:%d) in %d nsec}"/*,getQuery(), start, end*/);
    }

//    private String getQuery() {
//        return null;
//    }

    private boolean isExecMethod(Method method) {
        return false;
    }

    private Object doInvoke(Method method, Object[] args) throws Throwable {
        try {
            return method.invoke(jdbcObj, args);
        } catch (InvocationTargetException e) {
            //Here we try to get the origin of the exception. It must be a SQLException or a RuntimeException
            //we propagate the origin and not the reflect exception.
            if (e.getCause() != null) {
                throw e.getCause();
            }
            throw e;
        }
    }
}
